package com.ajax.browser;

import java.io.*;
import java.net.*;

public class RequestEngine {
	private static final String NORMAL_FORM_ENCODING = "application/x-www-form-urlencoded";

	public URLConnection getURLConnection(URL connectionUrl,
			ClientletRequest request, String method)
			throws IOException {
		URLConnection connection;
		boolean isPost = "POST".equalsIgnoreCase(method);
		connection = connectionUrl.openConnection();
		if (isPost)
			connection.setDoOutput(true);
		connection.setUseCaches(false);
		if (connection instanceof HttpURLConnection) {
			HttpURLConnection hconnection = (HttpURLConnection) connection;
			hconnection.setConnectTimeout(60000);
			hconnection.setReadTimeout(90000);
		}
		this.addRequestProperties(connection, request, method, connectionUrl);
		if (isPost) {
			ParameterInfo pinfo = request.getParameterInfo();
			this.postData(connection, pinfo, request.getAltPostData());
		}
		return connection;
	}

	private void addRequestProperties(URLConnection connection,
			ClientletRequest request, String requestMethod, URL connectionUrl)
			throws ProtocolException {
		UserAgent userAgent = request.getUserAgent();
		connection.addRequestProperty("User-Agent", userAgent.toString());
		connection.addRequestProperty("X-Java-Version",
				userAgent.getJavaVersion());
		String referrer = request.getReferrer();
		if (referrer != null) {
			connection.addRequestProperty("Referer", referrer);
		}
		if (connection instanceof HttpURLConnection) {
			HttpURLConnection hconnection = (HttpURLConnection) connection;
			hconnection.setRequestMethod(requestMethod);
		}
		Header[] headers = request.getExtraHeaders();
		if (headers != null) {
			for (int i = 0; i < headers.length; i++) {
				String headerName = headers[i].getName();
				if (headerName.startsWith("X-")) {
					connection.addRequestProperty(headerName,
							headers[i].getValue());
				}
			}
		}
	}
	
	
	private void postData(URLConnection connection, ParameterInfo pinfo,
			String altPostData) throws IOException {
		Parameter[] parameters = pinfo.getParameters();
		ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
		for (int i = 0; i < parameters.length; i++) {
			Parameter parameter = parameters[i];
			if(i != 0) {
				bufOut.write((byte) '&');
			}
			String name = parameter.getName();
			String encName = URLEncoder.encode(name, "UTF-8");
			String value = parameter.getValue();
			String encValue = URLEncoder.encode(value, "UTF-8");
			bufOut.write(encName.getBytes("UTF-8"));
			bufOut.write((byte) '=');
			bufOut.write(encValue.getBytes("UTF-8"));
		}
		byte[] postContent = bufOut.toByteArray();
		if (connection instanceof HttpURLConnection) {
			((HttpURLConnection) connection)
			.setFixedLengthStreamingMode(postContent.length);
		}
		connection.setRequestProperty("Content-Type", NORMAL_FORM_ENCODING);
		// connection.setRequestProperty("Content-Length",
		// String.valueOf(postContent.length));
		OutputStream postOut = connection.getOutputStream();
		postOut.write(postContent);
		postOut.flush();
	}
}
